package dg;

/**
 * r 系数
 */
public class PPMCC {
    public static void main(String[] args) {
        float[] A = {23F, 23F, 27F, 27F, 39F, 41F, 47F, 49F, 50F,
                52F, 54F, 54F, 56F, 57F, 58F, 58F, 60F, 61F};
        float[] B = {9.5F, 26.5F, 7.8F, 17.8F, 31.4F, 25.9F, 27.4F, 27.2F, 31.2F,
                34.6F, 42.5F, 28.8F, 33.4F, 30.2F, 34.1F, 32.9F, 41.2F, 35.7F};
        PPMCC ppmcc = new PPMCC();
        float r = ppmcc.R(A, B);
        System.out.println(r);
    }

    /**
     * 求 R 系数
     *
     * @param A
     * @param B
     */
    public float R(float[] A, float[] B) {
        int lengthA = A.length;
        int lengthB = B.length;
        if (lengthA != lengthB) {
            return 0F;
        }
        //获取均值
        float EA = E(A, lengthA);
        float EB = E(B, lengthB);
        System.out.println(EA + "   " + EB);
        //获取方差
        float DA = D(A, EA, lengthA);
        float DB = D(B, EB, lengthB);
        System.out.println(DA + "  " + DB);
        //获取乘积和
        float sumOfMultiply = getSumOfMultiply(A, B);
        return (sumOfMultiply - lengthA * EA * EB) / (lengthA * DA * DB);
    }

    /**
     * 获取两个数组中对应的索引相乘
     * 然后将乘积相加的和
     *
     * @param A
     * @param B
     * @return
     */
    private float getSumOfMultiply(float[] A, float[] B) {
        int length = A.length;
        float sumOfMultiply = 0;
        for (int i = 0; i < length; i++) {
            sumOfMultiply += A[i] * B[i];
        }
        return sumOfMultiply;
    }

    /**
     * 求方差
     *
     * @param nums
     * @param E
     */
    private float D(float[] nums, float E, int length) {
        int sum = 0;
        for (float num : nums) {
            sum += Math.pow(num - E, 2);
        }
        return (float) Math.sqrt(sum / length);
    }

    /**
     * 求均值
     *
     * @param nums
     * @return
     */
    private float E(float[] nums, int length) {
        float sum = 0F;
        for (float num : nums) {
            sum += num;
        }
        return sum / length;
    }
}
